package labox.innovation.gameserver.model.quest;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;

import javolution.util.FastMap;
import labox.innovation.config.Config;
import labox.innovation.db.core.L2DatabaseFactory;
import labox.innovation.gameserver.GameTimeController;
import labox.innovation.gameserver.cache.HtmCache;
import labox.innovation.gameserver.instancemanager.QuestManager;
import labox.innovation.gameserver.model.FuzeDropData;
import labox.innovation.gameserver.model.L2ItemInstance;
import labox.innovation.gameserver.model.actor.L2Character;
import labox.innovation.gameserver.model.actor.L2Npc;
import labox.innovation.gameserver.model.actor.instance.FuzeMonsterInstance;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.model.itemcontainer.PcInventory;
import labox.innovation.gameserver.network.SystemMessageId;
import labox.innovation.gameserver.network.serverpackets.InventoryUpdate;
import labox.innovation.gameserver.network.serverpackets.StatusUpdate;
import labox.innovation.gameserver.network.serverpackets.SystemMessage;
import labox.innovation.util.Rnd;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Luis Arias
 */
public final class QuestState {

	protected static final Logger _log = LoggerFactory.getLogger(Quest.class.getName());

	/**
	 *任务名称
	 */
	private final String _questName;

	/**
	 * 任务对应玩家
	 */
	private final FuzePcInstance _player;

	/**
	 * 状态
	 */
	private byte _state;
	
	/**
	 * 选择奖励物品ID
	 */
	private int selcetItemId;

	/**
	 * 保存对应值(name,value)
	 */
	private Map<String, String> _vars;

	/**
	 * 用来标记,知道何时退出任务并清理
	 */
	private boolean _isExitQuestOnCleanUp = false;

	/**
	 * Constructor of the QuestState : save the quest in the list of quests of
	 * the player.<BR/>
	 * <BR/>
	 * 保存玩家的任务到任务列表<BR/>
	 * <U><I>Actions :</U></I><BR/>
	 * <LI>Save informations in the object QuestState created (Quest, Player,
	 * Completion, State)</LI> <LI>Add the QuestState in the player's list of
	 * quests by using setQuestState()</LI> <LI>Add drops gotten by the quest</LI>
	 * <BR/>
	 * 
	 * @param quest
	 *            : quest associated with the QuestState 与状态相关的任务
	 * @param player
	 *            : L2PcInstance pointing out the player 对应的玩家实例
	 * @param state
	 *            : state of the quest 任务的状态
	 * @param completed
	 *            : boolean for completion of the quest 任务是否完成
	 */
	QuestState(Quest quest, FuzePcInstance player, byte state) {
		_questName = quest.getName();
		_player = player;

		// 给玩家加入一个任务状态
		getPlayer().setQuestState(this);

		// set the state of the quest
		_state = state;
	}

	public String getQuestName() {
		return _questName;
	}

	/**
	 * Return the quest
	 * 
	 * @return Quest
	 */
	public Quest getQuest() {
		return QuestManager.getInstance().getQuest(_questName);
	}

	/**
	 * Return the L2PcInstance
	 * @return L2PcInstance
	 */
	public FuzePcInstance getPlayer() {
		return _player;
	}

	/**
	 * 返回任务数据
	 * 
	 * @return Map<String, String> 2010-5-18
	 * @author lyh
	 */
	public Map<String, String> getVars() {
		return _vars;
	}

	/**
	 * 设置任务数据
	 * 
	 * @param vars
	 *            2010-5-18
	 * @author lyh
	 */
	public void setVars(Map<String, String> vars) {
		this._vars = vars;
	}

	/**
	 * Return the state of the quest
	 * @return State
	 */
	public byte getState() {
		return _state;
	}
	
	public void setSelectItemId(int itemId) {
		this.selcetItemId = itemId;
	}
	
	public int getSelectItemId() {
		return this.selcetItemId;
	}

	/**
	 * 是否完成
	 */
	public boolean isCompleted() {
		return (getState() == State.COMPLETED);
	}

	/**
	 * 是否开始
	 */
	public boolean isStarted() {
		return (getState() == State.STARTED);
	}

	/**
	 * Return state of the quest after its initialization.<BR><BR>
	 * <U><I>Actions :</I></U>
	 * <LI>Remove drops from previous state</LI>
	 * <LI>Set new state of the quest</LI>
	 * <LI>Add drop for new state</LI>
	 * <LI>Update information in database</LI>
	 * <LI>Send packet QuestList to client</LI>
	 * @param state
	 * @return object
	 */
	public Object setState(byte state) {
		// set new state if it is not already in that state
		if (_state != state) {
			_state = state;

			Quest.updateQuestInDb(this);
			// QuestList ql = new QuestList();

			// getPlayer().sendPacket(ql);
		}
		return state;
	}

	/**
	 * Add parameter used in quests. <br>
	 * 添加参数用于任务,不保存到数据库
	 * 
	 * @param var
	 *            : 任务变量名称
	 * @param val
	 *            : 任务变量值
	 * @return String (equal to parameter "val")
	 */
	public String setInternal(String var, String val) {
		if (_vars == null)
			_vars = new FastMap<String, String>();

		if (val == null)
			val = "";

		_vars.put(var, val);
		return val;
	}

	/**
	 * 添加参数用于任务,值同步到数据库<br>
	 * Return value of parameter "val" after adding the couple (var,val) in
	 * class variable "vars".<BR>
	 * <BR>
	 * <U><I>Actions :</I></U><BR>
	 * <LI>Initialize class variable "vars" if is null</LI> <LI>Initialize
	 * parameter "val" if is null</LI> <LI>Add/Update couple (var,val) in class
	 * variable FastMap "vars"</LI> <LI>If the key represented by "var" exists
	 * in FastMap "vars", the couple (var,val) is updated in the database. The
	 * key is known as existing if the preceding value of the key (given as
	 * result of function put()) is not null.<BR>
	 * If the key doesn't exist, the couple is added/created in the database</LI>
	 * 
	 * @param var
	 *            : String indicating the name of the variable for quest
	 * @param val
	 *            : String indicating the value of the variable for quest
	 * @return String (equal to parameter "val")
	 */
	public String set(String var, String val) {
		if (_vars == null)
			_vars = new FastMap<String, String>();

		if (val == null)
			val = "";

		// FastMap.put() returns previous value associated with specified key, or null if there was no mapping for key.
		String old = _vars.put(var, val);// 与 key 关联的旧值,如果 key 没有任何映射关系,则返回 null

		if (old != null)
			Quest.updateQuestVarInDb(this, var, val);
		else
			Quest.createQuestVarInDb(this, var, val);

		if ("cond".equals(var)) {
			try {
				int previousVal = 0;
				try {
					previousVal = Integer.parseInt(old);
				} catch (Exception ex) {
					previousVal = 0;
				}
				setCond(Integer.parseInt(val), previousVal);
			} catch (Exception e) {
				_log.error(getPlayer().getName() + ", " + getQuestName() + " cond [" + val + "] is not an integer.  Value stored, but no packet was sent: ", Config.SERVER_ID, e);
			}
		}

		return val;
	}

	/**
	 * Internally handles the progression of the quest so that it is ready for
	 * sending appropriate packets to the client<BR>
	 * 在内部处理了任务进度，以便它准备发送适当的数据包到客户端<BR>
	 * <U><I>Actions :</I></U><BR>
	 * <LI>Check if the new progress number resets the quest to a previous
	 * (smaller) step</LI> <LI>If not, check if quest progress steps have been
	 * skipped</LI> <LI>If skipped, prepare the variable completedStateFlags
	 * appropriately to be ready for sending to clients</LI> <LI>If no steps
	 * were skipped, flags do not need to be prepared...</LI> <LI>If the passed
	 * step resets the quest to a previous step, reset such that steps after the
	 * parameter are not considered, while skipped steps before the parameter,
	 * if any, maintain their info</LI>
	 * 
	 * @param cond
	 *            : int 表示当前任务进展的进度数（如将显示给客户端）
	 * @param old
	 *            : int 表示之前的进度
	 * 
	 *            For more info on the variable communicating the progress steps
	 *            to the client, please see
	 * @link labox.innovation.loginserver.serverpacket.QuestList
	 */
	private void setCond(int cond, int old) {
		int completedStateFlags = 0; // initializing...

		// 如果没有改变最后的设置,不在任何操作
		if (cond == old)
			return;

		// cond 0和1不需要completedStateFlags。此外，如果cond> 1，
		// 第一步骤都必须始终存在（即它不能被忽略）。
		// 因此，如果cond是2， 我们仍然可以安全地假设没有采取任何被跳过。最后，超过31步骤不能以任何方式予以支持与跳跃。
		if (cond < 3 || cond > 31) {
			unset("__compltdStateFlags");
		} else
			completedStateFlags = getInt("__compltdStateFlags");

		// case 1：目前没有进度...
		if (completedStateFlags == 0) {
			// check if this step also doesn't skip anything.  If so, no further work is needed
			// also, in this case, no work is needed if the state is being reset to a smaller value
			// in those cases, skip forward to informing the client about the change...

			// ELSE, if we just now skipped for the first time...prepare the flags!!!
			if (cond > (old + 1)) {
				// set the most significant bit to 1 (indicates that there exist skipped states)
				// also, ensure that the least significant bit is an 1 (the first step is never skipped, no matter
				// what the cond says)
				completedStateFlags = 0x80000001;

				// since no flag had been skipped until now, the least significant bits must all
				// be set to 1, up until "old" number of bits.
				completedStateFlags |= ((1 << old) - 1);

				// now, just set the bit corresponding to the passed cond to 1 (current step)
				completedStateFlags |= (1 << (cond - 1));
				set("__compltdStateFlags", String.valueOf(completedStateFlags));
			}
		}
		// case 2: 此前有存在进度
		else {
			// if this is a push back to a previous step, clear all completion flags ahead
			if (cond < old) {
				completedStateFlags &= ((1 << cond) - 1); // note, this also unsets the flag indicating that there exist skips

				//now, check if this resulted in no steps being skipped any more
				if (completedStateFlags == ((1 << cond) - 1))
					unset("__compltdStateFlags");
				else {
					// set the most significant bit back to 1 again, to correctly indicate that this skips states.
					// also, ensure that the least significant bit is an 1 (the first step is never skipped, no matter
					// what the cond says)
					completedStateFlags |= 0x80000001;
					set("__compltdStateFlags", String.valueOf(completedStateFlags));
				}
			}
			// if this moves forward, it changes nothing on previously skipped steps...so just mark this
			// state and we are done
			else {
				completedStateFlags |= (1 << (cond - 1));
				set("__compltdStateFlags", String.valueOf(completedStateFlags));
			}
		}

		// send a packet to the client to inform it of the quest progress (step change)
		//		QuestList ql = new QuestList();
		// getPlayer().sendPacket(ql);

		int questId = getQuest().getQuestIntId();
		// if (questId > 0 && questId < 19999 && cond > 0)
		//			getPlayer().sendPacket(new ExShowQuestMark(questId));
	}

	/**
	 * Remove the variable of quest from the list of variables for the quest.<BR>
	 * 除去任务变量从变量的任务列表<BR>
	 * <U><I>Concept : </I></U> Remove the variable of quest represented by
	 * "var" from the class variable FastMap "vars" and from the database.
	 * 
	 * @param var
	 *            : String designating the variable for the quest to be deleted
	 * @return String pointing out the previous value associated with the
	 *         variable "var"
	 */
	public String unset(String var) {
		if (_vars == null)
			return null;

		String old = _vars.remove(var);

		if (old != null)
			Quest.deleteQuestVarInDb(this, var);

		return old;
	}

	/**
	 * Insert (or Update) in the database variables that need to stay persistant for this player after a reboot.
	 * This function is for storage of values that do not related to a specific quest but are
	 * global for all quests.  For example, player's can get only once the adena and XP reward for  
	 * the first class quests, but they can make more than one first class quest.
	 * @param var : String designating the name of the variable for the quest
	 * @param value : String designating the value of the variable for the quest
	 */
	public final void saveGlobalQuestVar(String var, String value) {
		Connection con = null;
		try {
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement;
			statement = con.prepareStatement("REPLACE INTO character_quest_global_data (charId,var,value) VALUES (?,?,?)");
			statement.setLong(1, _player.getObjectId());
			statement.setString(2, var);
			statement.setString(3, value);
			statement.executeUpdate();
			statement.close();
		} catch (Exception e) {
			_log.error("could not insert player's global quest variable:", Config.SERVER_ID, e);
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Read from the database a previously saved variable for this quest.
	 * Due to performance considerations, this function should best be used only when the quest is first loaded.
	 * Subclasses of this class can define structures into which these loaded values can be saved.
	 * However, on-demand usage of this function throughout the script is not prohibited, only not recommended. 
	 * Values read from this function were entered by calls to "saveGlobalQuestVar"
	 * @param var : String designating the name of the variable for the quest
	 * @return String : String representing the loaded value for the passed var, or an empty string if the var was invalid
	 */
	public final String getGlobalQuestVar(String var) {
		String result = "";
		Connection con = null;
		try {
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement;
			statement = con.prepareStatement("SELECT value FROM character_quest_global_data WHERE charId = ? AND var = ?");
			statement.setLong(1, _player.getObjectId());
			statement.setString(2, var);
			ResultSet rs = statement.executeQuery();
			if (rs.first())
				result = rs.getString(1);
			rs.close();
			statement.close();
		} catch (Exception e) {
			_log.error("could not load player's global quest variable:", Config.SERVER_ID, e);
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * Permanently delete from the database one of the player's global quest variable that was previously saved.
	 * @param var : String designating the name of the variable
	 */
	public final void deleteGlobalQuestVar(String var) {
		Connection con = null;
		try {
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement;
			statement = con.prepareStatement("DELETE FROM character_quest_global_data WHERE charId = ? AND var = ?");
			statement.setLong(1, _player.getObjectId());
			statement.setString(2, var);
			statement.executeUpdate();
			statement.close();
		} catch (Exception e) {
			_log.error("could not delete player's global quest variable:", Config.SERVER_ID, e);
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Return the value of the variable of quest represented by "var"
	 * @param var : name of the variable of quest
	 * @return Object
	 */
	public Object get(String var) {
		if (_vars == null)
			return null;

		return _vars.get(var);
	}

	/**
	 * Return the value of the variable of quest represented by "var"
	 * @param var : String designating the variable for the quest
	 * @return int
	 */
	public int getInt(String var) {
		int varint = 0;

		try {
			if (_vars != null) {
				String result = _vars.get(var);
				if (result != null && !"".equals(result)) {
					varint = Integer.parseInt(_vars.get(var));
				}
			}   
		} catch (Exception e) {
			_log.error(getPlayer().getName() + ": variable " + var + " isn't an integer: " + varint, Config.SERVER_ID, e);
			//	    if (Config.AUTODELETE_INVALID_QUEST_DATA)
			//		exitQuest(true);
		}

		return varint;
	}

	/**
	 * Add player to get notification of characters death
	 * @param character : L2Character of the character to get notification of death
	 */
	public void addNotifyOfDeath(L2Character character) {
		if (character == null || !(character instanceof FuzePcInstance))
			return;

		((FuzePcInstance) character).addNotifyQuestOfDeath(this);
	}

	/**
	 * Return the quantity of one sort of item hold by the player
	 * @param itemId : ID of the item wanted to be count
	 * @return long
	 */
	public int getQuestItemsCount(int itemId) {
		int count = 0;

		for (L2ItemInstance item : getPlayer().getInventory().getItems())
			if (item != null && item.getItemId() == itemId)
				count += item.getCount();

		return count;
	}

	/**
	 * Return the level of enchantment on the weapon of the player(Done specifically for weapon SA's)
	 * @param itemId : ID of the item to check enchantment
	 * @return int
	 */
	public int getEnchantLevel(int itemId) {
		L2ItemInstance enchanteditem = getPlayer().getInventory().getItemByItemId(itemId);

		if (enchanteditem == null)
			return 0;

		return enchanteditem.getEnchantLevel();
	}

	/**
	 * Give adena to the player
	 * @param count
	 * @param applyRates
	 */
	public void giveAdena(int count, boolean applyRates) {
		giveItems(57, count, applyRates ? 0 : 1, "");
	}

	/**
	 * 给予物品
	 * 
	 * @param itemId
	 * @param count
	 * @param process
	 *            日志信息
	 */
	public void giveItems(int itemId, int count, String process) {
		giveItems(itemId, count, 0, process);
	}

	public void giveItems(int itemId, int count, int enchantlevel,
			String process) {
		if (count <= 0)
			return;

		// 物品添加到玩家的库存
		L2ItemInstance item = getPlayer().getInventory().addItem(process, itemId, count, getPlayer(), getPlayer().getTarget());

		if (item == null)
			return;

		// 设置物品强化等级,如果该物品不为货币
		if (enchantlevel > 0 && itemId != PcInventory.MONEY_SLIVER_ID && itemId != PcInventory.MONEY_NOTE_ID)
			item.setEnchantLevel(enchantlevel);

		// 如果奖励物品是黄金，黄金的奖励发送到客户端的信息
		if (itemId == PcInventory.MONEY_SLIVER_ID || itemId == PcInventory.MONEY_NOTE_ID) {
			SystemMessage smsg = new SystemMessage(SystemMessageId.EARNED_ADENA);
			smsg.addItemNumber(count);
			getPlayer().sendPacket(smsg);
		}
		// 否则，奖励对象发送到客户端的信息
		else {
			if (count > 1) {
				SystemMessage smsg = new SystemMessage(SystemMessageId.EARNED_S2_S1_S);
				smsg.addItemName(item);
				smsg.addItemNumber(count);
				getPlayer().sendPacket(smsg);
			} else {
				SystemMessage smsg = new SystemMessage(SystemMessageId.EARNED_ITEM);
				smsg.addItemName(item);
				getPlayer().sendPacket(smsg);
			}
		}
		// send packets
		StatusUpdate su = new StatusUpdate(getPlayer().getObjectId());
		// su.addAttribute(StatusUpdate.CUR_LOAD, getPlayer().getCurrentLoad());
		getPlayer().sendPacket(su);
	}

	public void giveItems(int itemId, int count, byte attributeId, int attributeLevel) {
		if (count <= 0)
			return;

		// Add items to player's inventory
		L2ItemInstance item = getPlayer().getInventory().addItem("Quest", itemId, count, getPlayer(), getPlayer().getTarget());

		if (item == null)
			return;

		// set enchant level for item if that item is not adena
		// if (attributeId >= 0 && attributeLevel > 0) {
		//			item.setElementAttr(attributeId, attributeLevel);
		// if (item.isEquipped())
		//				item.updateElementAttrBonus(getPlayer());

		//			InventoryUpdate iu = new InventoryUpdate();
		//			iu.addModifiedItem(item);
		//			getPlayer().sendPacket(iu);
		// }

		// If item for reward is gold, send message of gold reward to client
		if (itemId == 57) {
			SystemMessage smsg = new SystemMessage(SystemMessageId.EARNED_ADENA);
			smsg.addItemNumber(count);
			getPlayer().sendPacket(smsg);
		}
		// Otherwise, send message of object reward to client
		else {
			if (count > 1) {
				SystemMessage smsg = new SystemMessage(SystemMessageId.EARNED_S2_S1_S);
				smsg.addItemName(item);
				smsg.addItemNumber(count);
				getPlayer().sendPacket(smsg);
			} else {
				SystemMessage smsg = new SystemMessage(SystemMessageId.EARNED_ITEM);
				smsg.addItemName(item);
				getPlayer().sendPacket(smsg);
			}
		}
		// send packets
		StatusUpdate su = new StatusUpdate(getPlayer().getObjectId());
		// su.addAttribute(StatusUpdate.CUR_LOAD, getPlayer().getCurrentLoad());
		getPlayer().sendPacket(su);
	}

	/**
	 * Drop Quest item using Config.RATE_DROP_QUEST <br>
	 * 任务物品掉落率
	 * 
	 * @param itemId
	 *            : int 掉落物品id
	 * @param count
	 *            (minCount, maxCount) : int 物品的掉落数量
	 * @param neededCount
	 *            : 任务需要物品数量
	 * @param dropChance
	 *            : int 基础的下降几率
	 * @param sound
	 *            : boolean 指示是否播放声音
	 * @return boolean 是否要提示玩家已经获取数量
	 */
	public boolean dropQuestItems(int itemId, int count, int neededCount, int dropChance, boolean sound) {
		return dropQuestItems(itemId, count, count, neededCount, dropChance, sound);
	}

	public boolean dropQuestItems(int itemId, int minCount, int maxCount, int neededCount, int dropChance, boolean sound) {
		dropChance *= Config.RATE_DROP_QUEST / ((getPlayer().getParty() != null) ? getPlayer().getParty().getMemberCount() : 1);
		int currentCount = getQuestItemsCount(itemId);

		if (neededCount > 0 && currentCount >= neededCount)
			return true;

		if (currentCount >= neededCount)
			return true;

		int itemCount = 0;
		int random = Rnd.get(FuzeDropData.MAX_CHANCE);

		while (random < dropChance) {
			// 获得该物品的掉落数量
			if (minCount < maxCount)
				itemCount += Rnd.get(minCount, maxCount);
			else if (minCount == maxCount)
				itemCount += minCount;
			else
				itemCount++;

			// 准备下一次迭代 if dropChance > FuzeDropData.MAX_CHANCE
			dropChance -= FuzeDropData.MAX_CHANCE;
		}

		if (itemCount > 0) {
			// 如果超过需要数量，刚好填补了差值
			if (neededCount > 0 && currentCount + itemCount > neededCount)
				itemCount = neededCount - currentCount;

			// 库存箱位检查
			if (!getPlayer().getInventory().validateCapacityByItemId(itemId))
				return false;

			// 给与玩家物品
			getPlayer().addItem("Quest", itemId, itemCount, getPlayer().getTarget(), true);

			if (sound)
				playSound((currentCount + itemCount < neededCount) ? "Itemsound.quest_itemget" : "Itemsound.quest_middle");
		}

		return (neededCount > 0 && currentCount + itemCount >= neededCount);
	}

	// END STUFF THAT WILL PROBABLY BE CHANGED

	/**
	 * Remove items from player's inventory when talking to NPC in order to have
	 * rewards.<BR>
	 * npc对话时从玩家的清单移除物品，以便有奖励<BR>
	 * <U><I>Actions :</I></U> <LI>Destroy quantity of items wanted</LI> <LI>
	 * Send new inventory list to player</LI>
	 * 
	 * @param itemId
	 *            : 物品id
	 * @param count
	 *            : 删除物品数量
	 */
	public boolean takeItems(int itemId, int count, String process) {
		// 从玩家的库存清单对象获取物品
		L2ItemInstance item = getPlayer().getInventory().getItemByItemId(itemId);
		if (item == null)
			return false;

		// 计数值试验研究，以便不产生负值
		if (count < 0 || count > item.getCount())
			count = item.getCount();

		// Destroy the quantity of items wanted
		// if (itemId == 57)// 好像是需要扣除游戏币逻辑
		// getPlayer().reduceAdena("Quest", count, getPlayer(), true);
		//		else {
		if (item.isEquipped()) {// 判断是否已经装备
			L2ItemInstance[] unequiped = getPlayer().getInventory().unEquipItemInBodySlotAndRecord(item.getItem().getBodyPart());
			InventoryUpdate iu = new InventoryUpdate();
			for (L2ItemInstance itm : unequiped)
				iu.addModifiedItem(itm);
			getPlayer().sendPacket(iu);
			getPlayer().broadcastUserInfo();
		}
		return getPlayer().destroyItemByItemId(process, itemId, count, getPlayer(), true);
		// }
	}

	/**
	 * Send a packet in order to play sound at client terminal
	 * @param sound
	 */
	public void playSound(String sound) {
		// getPlayer().sendPacket(new PlaySound(sound));
	}

	/**
	 * Add XP and SP as quest reward
	 * @param exp
	 * @param sp
	 */
	public void addExpAndSp(int exp, int sp) {
		// getPlayer().addExpAndSp( getPlayer().calcStat(Stats.EXPSP_RATE,
		// (int)(exp * Config.RATE_QUESTS_REWARD), null, null),
		// getPlayer().calcStat(Stats.EXPSP_RATE, (int)(sp *
		// Config.RATE_QUESTS_REWARD), null, null));
	}

	/**
	 * Return random value
	 * @param max : max value for randomisation
	 * @return int
	 */
	public int getRandom(int max) {
		return Rnd.get(max);
	}

	/**
	 * Return number of ticks from GameTimeController
	 * @return int
	 */
	public int getItemEquipped(int loc) {
		return getPlayer().getInventory().getPaperdollItemId(loc);
	}

	/**
	 * Return the number of ticks from the GameTimeController
	 * @return int
	 */
	public int getGameTicks() {
		return GameTimeController.getGameTicks();
	}

	/**
	 * Return true if quest is to exited on clean up by QuestStateManager
	 * @return boolean
	 */
	public final boolean isExitQuestOnCleanUp() {
		return _isExitQuestOnCleanUp;
	}

	/**
	 * Return the QuestTimer object with the specified name
	 * @return QuestTimer<BR> Return null if name does not exist
	 */
	public void setIsExitQuestOnCleanUp(boolean isExitQuestOnCleanUp) {
		_isExitQuestOnCleanUp = isExitQuestOnCleanUp;
	}

	/**
	 * Start a timer for quest.<BR><BR>
	 * @param name<BR> The name of the timer. Will also be the value for event of onEvent
	 * @param time<BR> The milisecond value the timer will elapse
	 */
	public void startQuestTimer(String name, int time) {
		getQuest().startQuestTimer(name, time, null, getPlayer(), false);
	}

	public void startQuestTimer(String name, int time, L2Npc npc) {
		getQuest().startQuestTimer(name, time, npc, getPlayer(), false);
	}

	public void startRepeatingQuestTimer(String name, int time) {
		getQuest().startQuestTimer(name, time, null, getPlayer(), true);
	}

	public void startRepeatingQuestTimer(String name, int time, L2Npc npc) {
		getQuest().startQuestTimer(name, time, npc, getPlayer(), true);
	}

	/**
	 * Return the QuestTimer object with the specified name
	 * @return QuestTimer<BR> Return null if name does not exist
	 */
	public final QuestTimer getQuestTimer(String name) {
		return getQuest().getQuestTimer(name, null, getPlayer());
	}

	/**
	 * Add spawn for player instance
	 * Return object id of newly spawned npc
	 */
	public L2Npc addSpawn(int npcId) {
		return addSpawn(npcId, getPlayer().getX(), getPlayer().getY(), false, 0);
	}

	public L2Npc addSpawn(int npcId, int despawnDelay) {
		return addSpawn(npcId, getPlayer().getX(), getPlayer().getY(), false, despawnDelay);
	}

	public L2Npc addSpawn(int npcId, int x, int y) {
		return addSpawn(npcId, x, y, false, 0);
	}

	/**
	 * Add spawn for player instance
	 * Will despawn after the spawn length expires
	 * Uses player's coords and heading.
	 * Adds a little randomization in the x y coords
	 * Return object id of newly spawned npc
	 */
	public L2Npc addSpawn(int npcId, L2Character cha) {
		return addSpawn(npcId, cha, true, 0);
	}

	public L2Npc addSpawn(int npcId, L2Character cha, int despawnDelay) {
		return addSpawn(npcId, cha.getX(), cha.getY(), true, despawnDelay);
	}

	/**
	 * Add spawn for player instance
	 * Will despawn after the spawn length expires
	 * Return object id of newly spawned npc
	 */
	public L2Npc addSpawn(int npcId, int x, int y, int despawnDelay) {
		return addSpawn(npcId, x, y, false, despawnDelay);
	}

	/**
	 * Add spawn for player instance
	 * Inherits coords and heading from specified L2Character instance.
	 * It could be either the player, or any killed/attacked mob
	 * Return object id of newly spawned npc
	 */
	public L2Npc addSpawn(int npcId, L2Character cha, boolean randomOffset, int despawnDelay) {
		return addSpawn(npcId, cha.getX(), cha.getY(), randomOffset, despawnDelay);
	}

	/**
	 * Add spawn for player instance
	 * Return object id of newly spawned npc
	 */
	public L2Npc addSpawn(int npcId, int x, int y, boolean randomOffset, int despawnDelay) {
		return getQuest().addSpawn(npcId, x, y, randomOffset, despawnDelay, false);
	}

	/**
	 * Add spawn for player instance
	 * Return object id of newly spawned npc
	 */
	public L2Npc addSpawn(int npcId, int x, int y, boolean randomOffset, int despawnDelay, boolean isSummonSpawn) {
		return getQuest().addSpawn(npcId, x, y, randomOffset, despawnDelay, isSummonSpawn);
	}

	public String showHtmlFile(String fileName) {
		return getQuest().showXmlFile(getPlayer(), fileName);
	}

	/**
	 * Destroy element used by quest when quest is exited<br>
	 * 完成任务处理逻辑(当任务接收条件不符合时调用此方法删除该任务和玩家的关联),<br>
	 * <li>取消任务时也可以调用这个接口,repeatable=true
	 * 
	 * @param repeatable
	 * @return QuestState
	 */
	public QuestState exitQuest(boolean repeatable) {
		return QuestStateLogic.getInstance().exitQuestHandle(this, repeatable);
		// // 删除此角色notifyDeath列表这一任务，如果它在这个列表中
		// _player.removeNotifyQuestOfDeath(this);
		//
		// if (isCompleted())
		// return this;
		//
		// // 说任务完成
		// setState(State.COMPLETED);
		//
		// // 清理注册任务物品
		// int[] itemIdList = getQuest().getRegisteredItemIds();
		// if (itemIdList != null) {
		// for (int i = 0; i < itemIdList.length; i++)
		// takeItems(itemIdList[i], -1);
		// }
		//
		// // If quest is repeatable, delete quest from list of quest of the
		// player
		// // and from database (quest CAN be created again => repeatable)
		// // 如果任务是重复的，删除的玩家列表的任务和任务从数据库（任务可以再次接=>可重复）
		// if (repeatable) {
		// getPlayer().delQuestState(getQuestName());
		// Quest.deleteQuestInDb(this);
		//
		// _vars = null;
		// } else {
		// // Otherwise, delete variables for quest and update database (quest
		// CANNOT be created again => not repeatable)
		// // 否则，删除和更新的任务数据库变量（任务不能重复接=>不可重复）
		// if (_vars != null) {
		// for (String var : _vars.keySet())
		// unset(var);
		// }
		//
		// Quest.updateQuestInDb(this);
		// }
		// _player.refreshMayQuestList();// 刷新可接任务列表
		// _player.refreshQuestList();// 刷新已经任务列表
		// _player.removeQuestList(getQuestName());// 清除已接任务(如:放弃(完成)任务时刷新)
		// return this;
	}

	public void showQuestionMark(int number) {
		// getPlayer().sendPacket(new TutorialShowQuestionMark(number));
	}

	public void playTutorialVoice(String voice) {
		// getPlayer().sendPacket(new PlaySound(2, voice, 0, 0,
		// getPlayer().getX(), getPlayer().getY()));
	}

	/**
	 * 显示指南html
	 */
	public void showTutorialHTML(String html) {
		String text = HtmCache.getInstance().getHtm("data/scripts/quests/255_Tutorial/" + html);
		if (text == null) {
			_log.warn("missing html page data/scripts/quests/255_Tutorial/" + html, Config.SERVER_ID, "任务");
			text = "<html><body>File data/scripts/quests/255_Tutorial/" + html + " not found or file is empty.</body></html>";
		}
		// getPlayer().sendPacket(new TutorialShowHtml(text));
	}

	public void closeTutorialHtml() {
		// getPlayer().sendPacket(new TutorialCloseHtml());
	}

	public void onTutorialClientEvent(int number) {
		// getPlayer().sendPacket(new TutorialEnableClientEvent(number));
	}

	public void dropItem(FuzeMonsterInstance npc, FuzePcInstance player, int itemId, int count) {
		// npc.dropItem(player, itemId, count);
	}
}
